package logic

import (
	"context"
	"fmt"
	"fresh-box/freshrpc/freshrpc"
	"fresh-box/freshrpc/internal/svc"
	"fresh-box/model"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddHemaLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddHemaLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddHemaLogic {
	return &AddHemaLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddHemaLogic) AddHema(in *freshrpc.AddHemaRequest) (*freshrpc.AddHemaResponse, error) {
	// todo: add your logic here and delete this line
	var hema model.Hema
	tx := model.DB.Begin()
	model.DB.Where("name=?", in.Name).Find(&hema)
	if hema.ID != 0 {
		return nil, fmt.Errorf("商品名称已添加")
	}
	var class model.Class
	model.DB.Where("name=?", in.ClassName).Find(&class)
	if class.ID == 0 {
		m := model.Class{
			Name: in.ClassName,
		}
		err := tx.Create(&m).Error
		if err != nil {
			tx.Rollback()
			return nil, fmt.Errorf("分类添加失败")
		}
	}
	hema = model.Hema{
		Name:    in.Name,
		Price:   float64(in.Price),
		Img:     in.Img,
		ClassId: int64(class.ID),
	}
	err := tx.Create(&hema).Error
	if err != nil {
		tx.Rollback()
		return nil, fmt.Errorf("添加失败")
	}
	tx.Commit()
	return &freshrpc.AddHemaResponse{
		HemaId: int64(hema.ID),
	}, nil
}
